<template>
  <div class="bigbox">
    <div class="topbox">
      <el-form
        :model="form"
        ref="form"
        label-position="left"
        label-width="80px"
        onsubmit="return false"
      >
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="用电企业">
              <FilterSelect2
                v-model="form.companyId"
                :optionlist="companyList"
                :valuekey="{ name: 'name', value: 'id' }"
                @changeSelect="companyChange"
              ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="日期">
              <el-date-picker
                size="small"
                v-model="date"
                type="datetimerange"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="13" style="text-align: right">
            <el-form-item>
              <Twobtn @chaxun="chaxun" @chongzhi="chongzhi"></Twobtn>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="bodybox">
      <div class="top" v-loading="loading2">
        <div v-if="e2" id="ynqs" style="width: 100%; height: 100%"></div>
      </div>
      <div class="bottom">
        <div class="top2">
          <div class="tit2"></div>
          <div class="tabs">
            <span>
              <el-button size="small" type="primary" @click="exporttab">
                <i class="el-icon-upload2">导出</i>
              </el-button>
            </span>
          </div>
        </div>

        <el-table
          v-loading="tableLoading"
          :data="tableList"
          style="width: 99%"
          height="35vh"
          border
          ref="table"
          :header-cell-style="{
            background: '#f5f5f5',
            'text-align': 'center'
          }"
        >
          <template slot="empty">
            <el-empty description="暂无数据"></el-empty>
          </template>
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="100px"
          >
          </el-table-column>
          <el-table-column align="center" prop="time" label="时间段">
          </el-table-column>
          <el-table-column prop="className" label="设备名称"> </el-table-column>
          <el-table-column
            align="right"
            prop="runningTime"
            label="设备运行时间(h)"
          >
          </el-table-column>
          <el-table-column
            align="right"
            prop="runningRate"
            label="设备开动率(%)"
          >
            <template slot-scope="scope">
              {{ scope.row.runningRate.toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
        <!-- 底部分页 -->
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getCompanyListApi } from '@/api/energy-consumption/Equipment-energy/Energy-analysis'
import dayjs from 'dayjs'

import { exportexcel } from '@/utils/excel'
import {
  getTableListApi,
  getganttApi
} from '@/api/energy-consumption/Equipment-energy/Running-time'
export default {
  name: 'RunningTime',
  data() {
    return {
      form: {},
      tableList: [],
      date: [
        dayjs().subtract(1, 'week').format('YYYY-MM-DD HH:mm:ss'),
        dayjs().format('YYYY-MM-DD HH:mm:ss')
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      loading2: false,
      tableLoading: false,
      companyList: [],
      ganttList: [],
      e2: true
    }
  },
  async created() {
    await this.getCompanyList()
    await this.getdatalist()
  },
  methods: {
    companyChange(val) {
      localStorage.setItem('companyId', val)
    },
    // 获取用电企业列表
    async getCompanyList() {
      const res = await getCompanyListApi()
      console.log(res)
      this.companyList = res.data.list
      const companyId = +localStorage.getItem('companyId')
      if (companyId && this.companyList.find((i) => i.id == companyId)) {
        this.$set(this.form, 'companyId', companyId)
      } else {
        this.$set(this.form, 'companyId', this.companyList[0].id)
      }
    },
    // 初始化
    async getchushihua() {
      this.date = [
        dayjs().subtract(1, 'week').format('YYYY-MM-DD HH:mm:ss'),
        dayjs().format('YYYY-MM-DD HH:mm:ss')
      ]
      this.$set(this.form, 'companyId', this.companyList[0].id)
      this.$set(this.form, 'companyName', this.companyList[0].name)
      localStorage.setItem('companyId', this.companyList[0].id)
    },

    // 运行时间甘特图
    async getUsageLine() {
      this.e2 = false
      this.loading2 = true
      const res = await getganttApi({
        companyId: this.form.companyId,
        startDate: this.date[0],
        endDate: this.date[1]
      })
      console.log('2222', res.data.list)
      this.ganttList = res.data.list
      this.e2 = true
      this.loading2 = false
    },

    // 表格
    async getTableList() {
      this.e4 = false
      this.tableLoading = true
      const res = await getTableListApi({
        companyId: this.form.companyId,
        startDate: this.date[0],
        endDate: this.date[1]
      })
      this.tableList = res.data.list
      this.e4 = true
      this.tableLoading = false
    },
    exporttab() {
      exportexcel(
        '/ecm-microservice-biz/ecm/device/running/time/export',
        {
          companyId: this.form.companyId,
          startDate: this.date[0],
          endDate: this.date[1]
        },
        '设备运行时间'
      )
    },
    // 获取数据
    async getdatalist() {
      const promises = [this.getUsageLine().then(() => this.myChart2())]
      this.getTableList()

      // 等待所有Promise完成
      await Promise.all(promises)
    },

    myChart2() {
      const myChart2 = echarts.init(document.getElementById('ynqs'))
      // const data1 = [
      //   {
      //     name: 'a设备',
      //     datalist: [
      //       { startTime: '2024-06-21 06:00', duration: 60 },
      //       { startTime: '2024-06-21 09:00', duration: 30 },
      //       { startTime: '2024-06-21 11:00', duration: 40 }
      //     ]
      //   },
      //   {
      //     name: 'b设备',
      //     datalist: [
      //       { startTime: '2024-06-21 07:00', duration: 20 },
      //       { startTime: '2024-06-21 08:00', duration: 50 },
      //       { startTime: '2024-06-21 12:00', duration: 10 },
      //       { startTime: '2024-06-21 15:00', duration: 90 }
      //     ]
      //   },
      //   {
      //     name: 'c设备',
      //     datalist: [
      //       { startTime: '2024-06-21 07:00', duration: 20 },
      //       { startTime: '2024-06-21 08:00', duration: 50 },
      //       { startTime: '2024-06-21 12:00', duration: 10 },
      //       { startTime: '2024-06-21 15:00', duration: 90 }
      //     ]
      //   }
      // ]
      // const data2 = [
      //   {
      //     name: 'a设备',
      //     index: 0,
      //     datalist: [
      //       { startTime: 1711579200000, duration: 3600000 },
      //       { startTime: 1711590000000, duration: 1800000 },
      //       { startTime: 1711597200000, duration: 2400000 }
      //     ]
      //   },
      //   {
      //     name: 'b设备',
      //     index: 1,
      //     datalist: [
      //       { startTime: 1711582800000, duration: 1200000 },
      //       { startTime: 1711586400000, duration: 3000000 },
      //       { startTime: 1711600800000, duration: 600000 },
      //       { startTime: 1711611600000, duration: 5400000 }
      //     ]
      //   },
      //   {
      //     name: 'c设备',
      //     index: 2,
      //     datalist: [
      //       { startTime: 1711582800000, duration: 1200000 },
      //       { startTime: 1711586400000, duration: 3000000 },
      //       { startTime: 1711600800000, duration: 600000 },
      //       { startTime: 1711611600000, duration: 5400000 }
      //     ]
      //   }
      // ]
      const echartsColors = [
        '#5470c6',
        '#91cc75',
        '#fac858',
        '#ee6666',
        '#73c0de',
        '#3ba272',
        '#fc8452',
        '#9a60b4',
        '#ea7ccc',
        '#fe9a65',
        '#c05050',
        '#59678c',
        '#c9ab00',
        '#7eb00a',
        '#6f5553',
        '#c14089'
      ]
      const data = []
      const categories = this.ganttList.map((i, index) => {
        return {
          name: i.name,
          datalist: i.datalist,
          index: index,
          color: echartsColors[index % echartsColors.length]
        }
      })
      console.log('categories', categories)
      // Generate mock data
      categories.forEach(function (category, index) {
        // const baseTime = category.startTime
        console.log('category', category)
        category.datalist?.forEach(function (datalist, index) {
          const i = category.datalist[index]
          data.push({
            name: category.name,
            value: [
              category.index,
              i.startTime,
              i.startTime + i.duration,
              i.duration
            ],
            itemStyle: {
              normal: {
                color: category.color
              },
              borderRadius: [20, 20, 20, 20]
            }
          })
        })
      })
      function renderItem(params, api) {
        const categoryIndex = api.value(0)
        const start = api.coord([api.value(1), categoryIndex])
        const end = api.coord([api.value(2), categoryIndex])
        const height = api.size([0, 1])[1] * 0.6
        const rectShape = echarts.graphic.clipRectByRect(
          {
            x: start[0],
            y: start[1] - height / 2,
            width: end[0] - start[0],
            height: height
          },
          {
            x: params.coordSys.x,
            y: params.coordSys.y,
            width: params.coordSys.width,
            height: params.coordSys.height
          }
        )
        return (
          rectShape && {
            type: 'rect',
            transition: ['shape'],
            shape: { ...rectShape },
            style: api.style()
          }
        )
      }
      console.log(data)
      myChart2.setOption({
        tooltip: {
          formatter: function (params) {
            return (
              params.marker +
              params.name +
              ': ' +
              '<br>' +
              '开始时间' +
              ':' +
              dayjs(params.value[2]).format('YYYY-MM-DD HH:mm:ss') +
              '<br>' +
              '运行时间' +
              ':' +
              (params.value[3] / 3600000).toFixed(2) +
              '小时'
            )
          }
        },
        dataZoom: [
          {
            type: 'slider',
            filterMode: 'weakFilter',
            showDataShadow: false,
            xAxisIndex: 0,
            top: 380,
            labelFormatter: ''
          },
          {
            type: 'inside',
            xAxisIndex: 0,
            filterMode: 'weakFilter'
          },
          {
            type: 'slider',
            filterMode: 'weakFilter',
            showDataShadow: false,
            yAxisIndex: 0,
            right: 100,
            labelFormatter: ''
          },
          {
            type: 'inside',
            yAxisIndex: 0,
            filterMode: 'weakFilter'
          }
        ],
        grid: {
          height: 280
        },
        xAxis: {
          // min: startTime,
          scale: true,
          axisLabel: {
            formatter: function (val) {
              return dayjs(val).format('YYYY-MM-DD HH:mm:ss')
            }
          }
        },
        yAxis: {
          data: categories.map((i) => i.name)
        },
        series: [
          {
            type: 'custom',
            renderItem: renderItem,
            itemStyle: {
              opacity: 0.8,
              borderRadius: 50
            },
            encode: {
              x: [1, 2],
              y: 0
            },
            data: data
          }
        ]
      })
      window.addEventListener('resize', () => {
        // 图表响应处理
        myChart2.resize()
      })
    },
    chaxun() {
      this.getdatalist()
    },

    async chongzhi() {
      await this.getchushihua()
      this.getdatalist()
    }
  }
}
</script>

<style lang="scss" scoped>
.option {
  height: auto;
}

.bigbox {
  display: flex;
  flex-direction: column;
  padding: 10px;
  background-color: #f1f1f1;
  height: 100%;
  .topbox {
    background-color: #fff;
    padding: 20px 20px;
    box-sizing: border-box;
    height: 80px !important;
    width: 100% !important;
    margin-bottom: 10px;
    // transition-property: all;
    // transition-duration: 0.2s;
  }
  .bodybox {
    flex: 1;
    display: flex;
    flex-direction: column;
    .top {
      display: flex;
      background-color: #fff;
      height: 50%;
      width: 100%;
    }
    .bottom {
      flex: 1;
      background-color: #fff;
      padding: 0 20px;
      .top2 {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px;
        .tit2 {
          display: flex;
          align-items: center;

          font-weight: bold;
          img {
            margin-right: 10px;
          }
        }
        .tabs {
          .button {
            width: 60px;
            height: 32px;
            background-color: #1a90fe;
            color: #fff;
            border-radius: 3px;
            border: none;
          }
          i:hover {
            color: #2194ff;
            cursor: pointer;
          }
        }
      }
    }
  }
}
</style>
